// pages/pageUpdate/pageUpdate.ts

import { Ble501,DataResultInfo } from "../../lib/ble-501"
var sBle501:Ble501
Page({
  data: {
    device:<any>null,
    ssid:"",
    pwd:"",
    ip:"无",
    it:0,
  },
  upgradeData: new Uint8Array(0),
  appArray: new Array(),
  dfuSettingArray:new Array(),

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    
  },
  onUnload() {
    clearInterval(this.data.it)
    sBle501.disConnectDevice(()=>{})
  },
  onShow(){
    var device = wx.getStorageSync("device")
    if(!!device){
      device = JSON.parse(device)
      this.setData({
        device:device
      })
      sBle501 = new Ble501();
    } else {
      this.setData({
        device:null
      })
    }
  },
  onHide(){
    clearInterval(this.data.it)
  },
  bindSsidInput(e:any){
    this.setData({
      ssid: e.detail.value
    })
  },
  bindPwdInput(e:any){
    this.setData({
      pwd: e.detail.value
    })
  },
  onSave:function(){
    if(!!!this.data.ssid){
      wx.showToast({
        title:'请填写WIFI名称',
        icon:'error'
      })
      return
    }
    if(!!!this.data.pwd){
      wx.showToast({
        title:'请填写WIFI密码',
        icon:'error'
      })
      return
    }
    this.setData({ip:"无"})
    var device = this.data.device
    if (!!!device){
      wx.showToast({
        title: '请先连接设备',
        icon: 'none'
      })
      return;
    }
    var that = this;
    wx.showLoading({
      title:"正在设置WiFi"
    })
    sBle501.connectDevice(device.deviceId,function(res:any){
      sBle501.onConnectStatus = null
      // 判断连接是否成功
      if(res.data.connectStatus){
        // 延时3秒
        setTimeout(() => {
          // 设置wifi命令
          sBle501.setWifi(that.data.ssid,that.data.pwd)
          wx.showToast({
            title:"设置成功",
          })
        }, 3000);
      } else {
        wx.showToast({
          title:"连接失败",
          icon:"error"
        })
      }
    })
  },
  onGetIp:function(){
    var that = this;
    sBle501.getWifiIpAddress(function(result:DataResultInfo){
      let addr = result.data.split("=")
      if (addr.length <2){
        return
      }
      let ip = addr[1]
      let ip1 = ip.split("\n")
      that.setData({
        ip:ip1[0]
      })
   })
  }
})